#include <Windows.h>
#include <mmsystem.h>
#include <stdio.h>

#pragma comment(lib, "winmm.lib")

// 检查音乐是否正在播放
BOOL isPlaying();

void test1() {
    mciSendString("open lib/24.mp3 alias xxx", NULL, 0, NULL);
    // 添加 repeat 参数实现循环播放
    mciSendString("play xxx repeat", NULL, 0, NULL);

    // 保持程序运行，以便音乐能持续播放
    printf("音乐正在循环播放，按任意键退出...\n");
    system("pause");

    // 关闭音乐
    mciSendString("close xxx", NULL, 0, NULL);
}

int test2() {
    HWAVEOUT hWaveOut;
    WAVEHDR waveHeader;
    char buffer[44100 * 2];  // 假设44.1kHz、16位、双声道
    FILE* pcmFile;
    size_t bytesRead;

    // 打开音频设备
    WAVEFORMATEX waveFormat = {0};
    waveFormat.wFormatTag = WAVE_FORMAT_PCM;
    waveFormat.nChannels = 2;
    waveFormat.nSamplesPerSec = 44100;
    waveFormat.wBitsPerSample = 16;
    waveFormat.nBlockAlign =
        waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
    waveFormat.nAvgBytesPerSec =
        waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;

    MMRESULT result =
        waveOutOpen(&hWaveOut, WAVE_MAPPER, &waveFormat, 0, 0, CALLBACK_NULL);
    if (result != MMSYSERR_NOERROR) {
        printf("Failed to open waveOut device\n");
        return -1;
    }

    // 使用 FFmpeg 将 MP3 文件解码为 PCM 数据
    system(
        "ffmpeg -i lib/121.mp3 -f wav -acodec pcm_s16le -ar 44100 -ac 2 "
        "output.pcm");

    // 打开解码后的 PCM 文件
    if (fopen_s(&pcmFile, "output.pcm", "rb") != 0) {
        printf("Failed to open PCM file\n");
        waveOutClose(hWaveOut);
        return -1;
    }

    // 准备音频数据
    waveHeader.lpData = buffer;
    waveHeader.dwBufferLength = sizeof(buffer);
    waveHeader.dwFlags = 0;

    result = waveOutPrepareHeader(hWaveOut, &waveHeader, sizeof(WAVEHDR));
    if (result != MMSYSERR_NOERROR) {
        printf("Failed to prepare wave header\n");
        waveOutClose(hWaveOut);
        fclose(pcmFile);
        return -1;
    }

    // 播放音频
    while ((bytesRead = fread(buffer, 1, sizeof(buffer), pcmFile)) > 0) {
        waveHeader.dwBufferLength = bytesRead;
        result = waveOutWrite(hWaveOut, &waveHeader, sizeof(WAVEHDR));
        if (result != MMSYSERR_NOERROR) {
            printf("Failed to write wave data\n");
            waveOutUnprepareHeader(hWaveOut, &waveHeader, sizeof(WAVEHDR));
            waveOutClose(hWaveOut);
            fclose(pcmFile);
            return -1;
        }
        Sleep(100);  // 等待缓冲区播放
    }

    // 清理资源
    waveOutUnprepareHeader(hWaveOut, &waveHeader, sizeof(WAVEHDR));
    waveOutClose(hWaveOut);
    fclose(pcmFile);
    return 0;
}

int main() {
    test1();
    // test2();
    return 0;
}